// var proName =  window.location.pathname.substring(1,window.location.pathname.length);
// var proName = "/" +  proName.substring(0,proName.indexOf("/"));
// var baseApiPath = "http://"+window.location.host + proName + "/";
var proName = "PLWC-Web/";
var baseSitePath = "http://127.0.0.1:8080/" + proName;
var baseApiPath = "http://127.0.0.1:8088/" + proName;


var wsUrl = baseApiPath + "/springws/websocket";
var url = window.location.host.indexOf(':') == -1 ? window.location.host : window.location.host.substring(0, window.location.host.indexOf(':'))
var imgServerUrl = "http://" + url + ":6355";  //图片服务器地址

var SEPARATOR = 'ξ';

var user = getUserJsonObj();
//缓存系统数据字典  key 父键Key  value List<数据字典>
var dataDictMapList = new Map();
//缓存系统数据字典 Key 字典Key   value  数据字典  
var dataDictMap = new Map();

window.loadingCount = 0;
window.loadingMaps = new Map();
//打开遮罩层
var showLoading = function (random) {
    window.loadingCount++;
    window.loadingMaps.put(random, setTimeout(function () {
        $(".showLoadingWordbox").show();
        $(".overlayLoadingWord").css({
            'display': 'block',
            'opacity': '0.2'
        });

        $(".showLoadingWordbox").stop(true).animate({
            'top': '40%',
            'opacity': '1'
        }, 200);
    }, 500));
};

//打开遮罩层
var hideLoading = function (random) {
    if (--window.loadingCount == 0) {
        $(".showLoadingWordbox").hide();
        $(".showLoadingWordbox").stop(true).animate({
            'top': '40%',
            'opacity': '0'
        }, 400);

        $(".overlayLoadingWord").css({
            'display': 'none',
            'opacity': '0'
        });
    }
    window.clearInterval(window.loadingMaps.get(random));
};

var JsonpAjax = function (url, paramObj, callback, type, dataType, contentType, useAsync) {
    if (!dataType) dataType = "json";
    if (!type) type = "POST";
    // if (!contentType) contentType = 'application/x-www-form-urlencoded';
    // else
    if (!contentType) contentType = 'application/json';
    var resultData = null;
    try {
        var random = Math.round(Math.random() * 1000000);
        showLoading(random);
        $.ajax({
            type: type,// 使用post方法访问后台
            contentType: contentType,
            dataType: dataType,// 返回数据的格式
            async: useAsync == false ? false : true,
            url: url,
            data: paramObj,// 参数
            error: function (e) {
                console.log("error: " + e.name);
                console.log("error: " + e.message);
                hideLoading(random);
                if (e.status == 336699) {   //336699表示未登录或者登录超时
                    loginTimeOut();
                    return;
                }
            },
            success: function (result) {// msg为返回的数据，在这里做数据绑定
                hideLoading(random);
                if (result) {
                    if (result.constructor == Object) {
                        if (0 != result.code) {
                            var messageText = t(result.message == null ? "" : result.message);
                            if (!isNotEmpt(messageText)) {
                                messageText = result.message;
                            }
                            notification({title: "操作失败", message: messageText}, 'error');
                            return;
                        } else if (0 === result.code) {
                            var messageText = t(result.message == null ? "" : result.message);
                            if (!isNotEmpt(messageText)) {
                                messageText = result.message;
                            }
                            if (result.constructor == Object && result.message) {
                                notification({title: "操作成功", message: messageText}, 'success');
                            } else {
                                if (!result) {
                                    result = new Object();
                                }
                            }
                            if (typeof callback == "function") {
                                eval(callback)(result);
                            }
                        } else {
                            if (typeof callback == "function") {
                                eval(callback)(result);
                            }
                        }
                    } else {
                        if (typeof callback == "function") {
                            eval(callback)(result);
                        }
                    }
                    resultData = result;
                }
            }
        });
    } catch (e) {
        console.log(e);
    }
    return resultData;
};


function isNotEmpt(str) {
    if (str != null && $.trim(str) != "" && str != "undefined")
        return true;
    else
        return false;
};

//国际化kendoUI的提示信息
function msgGrouble(e) {
    if ("Are you sure you want to delete this record?" == e) {
        return t("goableMessage.deleteMsg");
    }
    return e;
}


jQuery.extend({
    /**
     * *
     *
     * @see 将javascript数据类型转换为json字符串 *
     * @param 待转换对象,支持object,array,string,function,number,boolean,regexp *
     * @return 返回json字符串
     */
    toJSON: function (object) {
        if (object == null) {
            return undefined;
        }
        var type = typeof object;
        if ('object' == type) {
            if (Array == object.constructor) type = 'array';
            else if (RegExp == object.constructor) type = 'regexp';
            else type = 'object';
        }
        switch (type) {
            case 'undefined':
            case 'unknown':
                return;
                break;
            case 'function':
            case 'boolean':
            case 'regexp':
                return object.toString();
                break;
            case 'number':
                return isFinite(object) ? object.toString() : 'null';
                break;
            case 'string':
                return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g, function () {
                    var a = arguments[0];
                    return (a == '\n') ? '\\n' : (a == '\r') ? '\\r' : (a == '\t') ? '\\t' : ""
                }) + '"';
                break;
            case 'object':
                if (object === null) return 'null';
                var results = [];
                for (var property in object) {
                    var value = jQuery.toJSON(object[property]);
                    if (value !== undefined) results.push(jQuery.toJSON(property) + ':' + value);
                }
                return '{' + results.join(',') + '}';
                break;
            case 'array':
                var results = [];
                for (var i = 0; i < object.length; i++) {
                    var value = jQuery.toJSON(object[i]);
                    if (value !== undefined) results.push(value);
                }
                return '[' + results.join(',') + ']';
                break;
        }
    }
});


/**
 * 全选或者反选grid里面的checkbox
 * @param arg
 */
function gridCheckAll(arg) {
    var gridId = $(arg).attr("gridId");
    if (isEmpty(gridId)) return;
    var checkbox = $(arg).parents("div[id='" + gridId + "']").find("input[type='checkbox']");
    checkbox.each(function () {
        this.checked = arg.checked;
    });
}

/**
 * 是否全屏展示页面
 * @param isFullScreen
 */
function fullScreen(isFullScreen, dataTargetObj) {
    var targetObj = $("#sysMainDiv");
    if (isFullScreen) {   //全屏

        targetObj.find(".side-panel").hide();
        targetObj.find(".functions-panel").hide();
        targetObj.find(".header-panel").hide();
        targetObj.find(".footer-panel").hide();
        window.rightColumnLeft = targetObj.find(".innerContent").css("margin-left");
        window.rightColumnTop = targetObj.find(".innerContent-panel").css("top");
        targetObj.find(".innerContent-panel").css("top", "0px");
        targetObj.find(".innerContent").css("margin-left", "0px");
        var maxHeight = $(window).height() - 2;
        var maxWidth = $(window).width() - 2;
        targetObj.find("#rightDataDiv").css({
            height: maxHeight,
            width: maxWidth
        });
        kendoUtils.prototype.resetDviSize(dataTargetObj);
    } else {
        targetObj.find(".side-panel").show();
        targetObj.find(".functions-panel").show();
        targetObj.find(".header-panel").show();
        targetObj.find(".footer-panel").show();
        targetObj.find(".innerContent-panel").css("top", "108px");
        targetObj.find(".innerContent").css("margin-left", window.rightColumnLeft);
        targetObj.find(".innerContent-panel").css("top", window.rightColumnTop);
        adjustWindowSize();
    }
    if (screenfull != false) {
        screenfull.toggle(document.documentElement);
    }

}


function getLocalStorage(objKey) {
    if (window.localStorage) {
        var storageItem = JSON.parse(window.localStorage.getItem(user.userId));
        if (isNotEmpt(storageItem)) {
            var objData = storageItem[objKey];
            if (isNotEmpt(objData)) {
                return objData;
            } else {
                return null;
            }
        } else {
            return null;
        }
    } else {
        return null;
    }
}

function setLocalStorage(objKey, objValue) {
    if (window.localStorage) {
        var storageItem = JSON.parse(window.localStorage.getItem(user.userId));
        if (isNotEmpt(storageItem)) {
            storageItem[objKey] = objValue;
            window.localStorage.setItem(user.userId, JSON.stringify(storageItem));
        } else {
            window.localStorage.setItem(user.userId, JSON.stringify({objKey: objValue}));
        }

    } else {
        return false;
    }
}

//日期格式化代码

Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours() == 0 ? 12 : this.getHours(), // 小时
        "H+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    var m = {
        "s": "m",
        "d": "h"
    };
    return fmt;
};

//验证数组方法
Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}


/**字符串转换为时间*/
function stringToDate(str) {
    return new Date(Date.parse(str.replace(/-/g, "/")));
}

/**
 * 扩展String方法
 */
$.extend(String.prototype, {
    isPositiveInteger: function () {
        return (new RegExp(/^[1-9]\d*$/).test(this));
    },
    isInteger: function () {
        return (new RegExp(/^\d+$/).test(this));
    },
    isNumber: function (value, element) {
        return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
    },
    trim: function () {
        return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
    },
    startsWith: function (pattern) {
        return this.indexOf(pattern) === 0;
    },
    endsWith: function (pattern) {
        var d = this.length - pattern.length;
        return d >= 0 && this.lastIndexOf(pattern) === d;
    },
    replaceSuffix: function (index) {
        return this.replace(/\[[0-9]+\]/, '[' + index + ']').replace('#index#', index);
    },
    trans: function () {
        return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');
    },
    replaceAll: function (os, ns) {
        return this.replace(new RegExp(os, "gm"), ns);
    },
    replaceTm: function ($data) {
        if (!$data) return this;
        return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})", "g"), function ($1) {
            return $data[$1.replace(/[{}]+/g, "")];
        });
    },
    replaceTmById: function (_box) {
        var $parent = _box || $(document);
        return this.replace(RegExp("({[A-Za-z_]+[A-Za-z0-9_]*})", "g"), function ($1) {
            var $input = $parent.find("#" + $1.replace(/[{}]+/g, ""));
            return $input.val() ? $input.val() : $1;
        });
    },
    isFinishedTm: function () {
        return !(new RegExp("{[A-Za-z_]+[A-Za-z0-9_]*}").test(this));
    },
    skipChar: function (ch) {
        if (!this || this.length === 0) {
            return '';
        }
        if (this.charAt(0) === ch) {
            return this.substring(1).skipChar(ch);
        }
        return this;
    },
    isValidPwd: function () {
        return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this));
    },
    isValidMail: function () {
        return (new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
    },
    isSpaces: function () {
        for (var i = 0; i < this.length; i += 1) {
            var ch = this.charAt(i);
            if (ch != ' ' && ch != "\n" && ch != "\t" && ch != "\r") {
                return false;
            }
        }
        return true;
    },
    isPhone: function () {
        return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
    },
    isUrl: function () {
        return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
    },
    isExternalUrl: function () {
        return this.isUrl() && this.indexOf("://" + document.domain) == -1;
    }
});

/**
 * 根据长度截取先使用字符串，超长部分追加…
 * str 对象字符串
 * len 目标字节长度
 * 返回值： 处理结果字符串
 */
function cutString(str, len) {
    if (str.length * 2 <= len) {
        return str;
    }
    var strlen = 0;
    var s = "";
    for (var i = 0; i < str.length; i++) {
        s = s + str.charAt(i);
        if (str.charCodeAt(i) > 128) {
            strlen = strlen + 2;
            if (strlen >= len) {
                return s.substring(0, s.length - 1) + "...";
            }
        } else {
            strlen = strlen + 1;
            if (strlen >= len) {
                return s.substring(0, s.length - 2) + "...";
            }
        }
    }
    return s;
}

//初始化用户信息
function getUserJsonObj() {
    var name = "user_c";
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        var user_info = unescape(arr[2]);
        var userInfo = JSON.parse(user_info);
        return userInfo;
    } else {
        return null;
    }
}

//删除Cookie
function delUserJsonObj() {
    var name = "user_c";
    var date = new Date();
    date.setTime(date.getTime() - 2000);
    document.cookie = name + "=null; expires=" + date.toGMTString();
}


/**
 * 限时退出登录系统
 */
function loginTimeOut() {
    notification({title: "登录超时", message: "登录已超时,请您重新登录!!"}, "info");
    setTimeout(function () {
        window.location.href = "login.html";
    }, 2000);
}


//集中管理websocket连接，当页面关闭时，关闭对应的websocket连接
var websocketFun = function () {
    this.websocketMap = new Map();
    return this;
};

websocketFun.prototype = {
    /**
     * 添加websocket连接
     */
    addWebSocket: function (superDiv, websocket) {
        if (isEmpty(websocket) && isEmpty(superDiv)) return;
        var dataCode = superDiv.parents("li").attr("data-code");
        if (isEmpty(dataCode)) return;
        var oldWebSocket = this.websocketMap.get(dataCode);
        this.websocketMap.put(dataCode, websocket);
    },

    /**
     * 移除websocket连接，并关闭与后台通讯
     */
    removeWebSocket: function (dataCode) {
        var oldWebSocket = this.websocketMap.get(dataCode);
        if (null != oldWebSocket) {
            this.websocketMap.remove(dataCode);
            oldWebSocket.closeWebSocket();
        }
    }
}

var websocketFunManager = new websocketFun();
